package com.keyue.common.utils;

import com.keyue.common.constant.ServerResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @date 2023-02-02
 */
@Slf4j
public class ServletUtils {


    public static void renderServerResult(HttpServletResponse response, ServerResult serverResult, HttpStatus httpStatus) {
        try {
            response.setStatus(httpStatus.value());
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(JsonUtil.toJsonString(serverResult));
        } catch (IOException e) {
            log.error("ServletUtils#renderServerResult:", e);
        }
    }


    public static void renderExcelFileNotFound(HttpServletResponse response) {
        try {
            response.setStatus(404);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");
            response.sendError(HttpStatus.NOT_FOUND.value(), "下载失败，资源不存在");
        } catch (IOException e) {
            log.error("ServletUtils#renderWithResourceNotFound:", e);
        }
    }
}
